package basic.commons.page;

import java.io.Serializable;
import java.util.List;

//import com.google.common.base.Joiner;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
public class Page implements Serializable {

	private static final long serialVersionUID = 587754556498974978L;

	// pagesize ，每一页显示多少
	private int pageSize = 1;
	// 总页数
	private int totalPage;
	// 总记录数
	private Integer totalCount;
	// 当前页数
	private int currentPage;
	// 当前显示到的ID, 在mysql limit 中就是第一个参数.
	// private int currentResult;
	private String sortField;
	private String order;
	private List<?> result;

	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("\npagesize=" + pageSize);
		buffer.append("\ntotalpage=" + totalPage);
		buffer.append("\ncurrentpage=" + currentPage);
		// buffer.append(")
		return buffer.toString();
	}

	public List<?> getResult() {
		return result;
	}

	public void setResult(List<?> result) {
		this.result = result;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public Integer getTotalCount() {
		if (null == this.totalCount) {
			return 0;
		}
		return totalCount;
	}

	public void setTotalCount(Integer totalCount) {
		this.totalCount = totalCount;
		totalPage = this.calculatePages();

		// if (totalPage < currentPage) {
		// if (totalPage > 0) {
		// this.currentPage = totalPage;
		// } else {
		// this.currentPage = 1;
		// }
		// }
	}

	private int calculatePages() {
		if (totalCount > 0 && totalCount <= pageSize) {
			return 1;
		} else if (totalCount == 0) {
			return 0;
		} else if (totalCount % pageSize > 0) {
			return (int) totalCount / pageSize + 1;
		}
		return (int) totalCount / pageSize;
	}

	public int getCurrentPage() {
		// 如果totalCount没有值，则保持currentPage
		if (this.totalCount == null && this.currentPage > 0) {
			return this.currentPage;
		}
		int totalCount = getTotalCount();
		int lastPage = 0;
		if (currentPage > 0) {
			lastPage = totalCount / pageSize;
			if (totalCount % pageSize > 0) {
				lastPage += 1;
			}
			if (currentPage >= lastPage) {
				currentPage = lastPage;
			}
			return currentPage;
		}

		return 1;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public String getSortField() {
		return sortField;
	}

	public void setSortField(String sortField) {
		this.sortField = sortField;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public int getCurrentResult() {
		if (currentPage <= 0) {
			currentPage = 1;
		}
		int fromPos = (currentPage - 1) * pageSize;
		if (fromPos < 0) {
			fromPos = 0;
		}
		return fromPos;
	}
}
